package com.open.party.cloud.view.home.article.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.android.x.inters.AndroidView
import cn.android.x.model.data.AppPageData
import cn.android.x.model.data.PageReq
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppRecycleViewBaseFragment
import com.open.party.cloud.R
import com.open.party.cloud.model.ArticleEntity
import com.open.party.cloud.model.ArticleVo
import com.open.party.cloud.model.DictionaryBean
import com.open.party.cloud.model.SlideshowListBean
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.view.comm.view.banner.CustomViewHolder
import com.open.party.cloud.view.home.article.ArticleDetailsActivity
import com.open.party.cloud.view.home.article.adapter.ArticleListAdapter
import com.open.party.cloud.view.redMeeting.HuanJieGongZuoMainActivity
import com.open.party.cloud.view.redMeeting.QiYiJiangHuaMainActivity
import com.open.party.cloud.view.redMeeting.RedMeeting2MainActivity
import com.open.party.cloud.view.redMeeting.RedMeetingMainActivity
import com.open.party.cloud.viewModel.ArticlePresent
import com.open.party.cloud.viewModel.ArticleViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.android.utils.inters.OnSuperListener
import com.sinothk.banner.nice.Banner
import com.sinothk.banner.nice.BannerConfig
import com.sinothk.banner.nice.Transformer
import com.sinothk.rxretrofit.bean.PageVo
import com.sinothk.view.image.rounded.RoundedImageView
import com.sinothk.widget.loadingRecyclerView.extend.LoadingRecycleViewHeader
import kotlinx.android.synthetic.main.comm_fragment_rv_loading_list.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


open class ArticleListForMainFragment : AppRecycleViewBaseFragment<ArticleEntity>(), OnSuperListener<ArticleEntity>,
    AndroidView<ResultInfo<AppPageData<ArticleEntity>>> {

    protected var viewModel: ArticlePresent? = null
    private var adapter: ArticleListAdapter? = null
    private var currView: View? = null
    private var type: String? = null

    private var articleViewModel: ArticleViewModel? = null


    override fun onAttach(context: Context) {
        super.onAttach(context)
        type = arguments!!.getString("type")
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (currView == null) {
            currView = inflater.inflate(R.layout.comm_fragment_rv_loading_list, container, false)
        }
        return currView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = ArticlePresent(this)
        articleViewModel = ArticleViewModel()

        initRecycleLinearView(loadingRecyclerView)
        loadingRecyclerView.addHeaderView(createHeaderView())

        adapter = ArticleListAdapter(activity)
        loadingRecyclerView.adapter = adapter
        adapter?.setOnSuperListener(this)

        loadingTipView.setRetryListener {
            loadingTipView.showLoading("努力加载中")
            refreshData()
        }

        loadingTipView.showLoading("努力加载中")
        refreshData()
        initViewListData("HOME_LBXW")

        showCacheData()
    }

    private fun showCacheData() {
        val records: MutableList<ArticleEntity>? = LocalCache.getBannerData()
        if (records != null && records.size > 0) {
            initBannerView(records)
        }

        // 数据部分
        val contentData: AppPageData<ArticleEntity>? = LocalCache.getContentData()
        if ("HOME_SZYW" == type && contentData != null && contentData.size > 0) {
            setPageData(contentData)
            loadingTipView.showContent()
        }
    }

    override fun loadData(pageVo: PageVo<ArticleEntity>) {
        val pageReq = PageReq<ArticleVo>()
        pageReq.pageNo = pageVo.pageNum
        pageReq.pageSize = pageVo.pageSize
        val vo = ArticleVo()
        vo.childrenType = DictionaryBean(type, "")
        pageReq.data = vo

        viewModel!!.getArticleListData(pageReq)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<AppPageData<ArticleEntity>>) {
    }

    private fun setPageData(appPageData: AppPageData<ArticleEntity>) {
        if (loadType == LoadType.REFRESH) {
            if (appPageData.records.size == 0) {
                loadingTipView.showEmpty("暂无数据", R.drawable.empty_nodata)
                loadingRecyclerView.setLoadingMoreEnabled(false)
            } else {
                adapter!!.setData(appPageData.records!!)
                loadingTipView?.showContent()
            }
        } else {
            if (appPageData.records.size == 0) {
                tip("没有更多数据了")
            } else {
                adapter!!.updateData(appPageData.records!!)
                loadingTipView?.showContent()
            }
        }

        // 设置：通用
        if (appPageData.current < appPageData.pages) {
            loadingRecyclerView.setLoadingMoreEnabled(true)
        } else {
            loadingRecyclerView.setLoadingMoreEnabled(false)
            loadingRecyclerView.setNoMore(true)
        }
        stopLoading(loadingRecyclerView, loadType)
    }

    override fun onClick(position: Int, itemData: ArticleEntity, flag: String?) {
        if (!itemData.isExternalLink) {
            XUtils.intent().openActivity(activity, ArticleDetailsActivity::class.java)
                .putStringExtra("id", itemData.id)
                .startInFragment(this)
        } else {
            val intent = Intent()
            intent.action = "android.intent.action.VIEW"
            val contentUrl: Uri = Uri.parse(itemData.source)
            intent.data = contentUrl
            startActivity(intent)
        }
    }

    override fun loadingDismiss() {
    }

    override fun complete(result: ResultInfo<AppPageData<ArticleEntity>>) {
        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    setPageData(result.data)

                    if ("HOME_SZYW" == type) {
                        LocalCache.setContentData(result.data)
                    }
                } else {
                    loadingTipView.showError("数据异常")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
                loadingTipView.showError("Token过期，请重新登录")
            }
            else -> {
                loadingTipView?.showError(result.msg)
            }
        }
    }

    override fun loadingShow() {
    }

    override fun showTip(msg: String?) {
    }

    var bannerView: Banner? = null

    //    var homeHotTv: TextView? = null
//    var hitNews02Tv: TextView? = null
//    private var hitNewsItem: RelativeLayout? = null
//    var hitNews02Item: RelativeLayout? = null
    var hitNews01Icon: RoundedImageView? = null
    var hitNews02Icon: RoundedImageView? = null
    var hitNews03Icon: RoundedImageView? = null
    var hitNews05Icon: RoundedImageView? = null
    var hitNews06Icon: RoundedImageView? = null

    @SuppressLint("SetTextI18n")
    private fun createHeaderView(): View {
        val headerView: View = LoadingRecycleViewHeader.getViewByLayoutId(activity, R.layout.home_fragment_header_view)
        bannerView = headerView.findViewById(R.id.bannerView)
//        hitNewsItem = headerView.findViewById(R.id.hitNewsItem)
//        homeHotTv = headerView.findViewById(R.id.homeHotTv)

//        hitNews02Item = headerView.findViewById(R.id.hitNews02Item)
//        hitNews02Tv = headerView.findViewById(R.id.hitNews02Tv)

        hitNews01Icon = headerView.findViewById(R.id.hitNews01Icon)
        hitNews02Icon = headerView.findViewById(R.id.hitNews02Icon)
        hitNews03Icon = headerView.findViewById(R.id.hitNews03Icon)
        hitNews05Icon = headerView.findViewById(R.id.hitNews05Icon)
        hitNews06Icon = headerView.findViewById(R.id.hitNews06Icon)
        return headerView
    }

    private fun initViewListData(type: String) {
        val pageReq = PageReq<ArticleVo>()
        pageReq.pageNo = 1
        pageReq.pageSize = 6
        val vo = ArticleVo()
        vo.childrenType = DictionaryBean(type, "")
        pageReq.data = vo

        articleViewModel!!.getArticleListData(pageReq, type)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun receiveStudentEventBus(result: ResultInfo<AppPageData<ArticleEntity>>) {

        if ("HOME_LBXW" == result.eventType || "HOME_SZYW" == result.eventType || "HOME_TZGG" == result.eventType) {

            when (result.code) {
                ResultInfo.SUCCESS -> {
                    if (result.data != null && result.data.records != null) {

                        when (result.eventType) {
                            "HOME_LBXW" -> {
                                initBannerView(result.data.records)
                            }
                        }

                    } else {
                    }
                }
                ResultInfo.TOKEN_OVERDUE -> {
                    // 不存在
                }
                else -> {
                    XUtils.toast().show(result.msg)
                }
            }
        } else {
            return
        }
    }

    /**
     * 轮播图
     */
    private fun initBannerView(records: MutableList<ArticleEntity>) {
//        val fontFace = Typeface.createFromAsset(activity!!.assets, "fonts/FZXBSJW.TTF")
//        homeHotTv!!.typeface = fontFace
//        hitNews02Tv!!.typeface = fontFace
//
//        hitNewsItem!!.visibility = View.VISIBLE

        hitNews05Icon!!.setOnClickListener {
            XUtils.intent().openActivity(activity, RedMeetingMainActivity::class.java).start()
        }

        hitNews02Icon!!.setOnClickListener {
            XUtils.intent().openActivity(activity, RedMeeting2MainActivity::class.java).start()
        }

        hitNews01Icon!!.setOnClickListener {
            val intent = Intent()
            intent.action = "android.intent.action.VIEW"
            val contentUrl: Uri = Uri.parse("http://www.12371.cn/")
            intent.data = contentUrl
            startActivity(intent)
        }

        hitNews03Icon!!.setOnClickListener {
            XUtils.intent().openActivity(activity, HuanJieGongZuoMainActivity::class.java).start()
        }

        hitNews06Icon!!.setOnClickListener {
            XUtils.intent().openActivity(activity, QiYiJiangHuaMainActivity::class.java).start()
        }

//        val bW = bannerView!!.width
//        val bH = bannerView!!.height
//
//        if (bH == null) {
//        }

        LocalCache.setBannerData(records)
        showBanner(records)
    }

    private fun showBanner(records: MutableList<ArticleEntity>) {

        val titles: ArrayList<String> = java.util.ArrayList()
        val bannerList: ArrayList<SlideshowListBean> = ArrayList()
        for (item in records) {
            titles.add(item.theme)
            bannerList.add(SlideshowListBean(item.id, item.imgUrl))
        }

        bannerView!!.setBannerTitles(titles)
            .setAutoPlay(true)
            .setPages(bannerList, CustomViewHolder())
            .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
            .setBannerAnimation(Transformer.Default)
            .setDelayTime(3000)
            .start()

        bannerView!!.setOnBannerClickListener { _, position ->
            val id = bannerList[position].id
            if (TextUtils.isEmpty(id)) {
                return@setOnBannerClickListener
            }
            XUtils.intent().openActivity(activity, ArticleDetailsActivity::class.java)
                .putStringExtra("id", bannerList[position].id)
                .startInFragment(this)
        }
    }
}